<template>
    <div class="main-contain" style="width: 820px;">
      <p class="page-title">会员信息</p>
      <div class="profile-div" v-if="userData.user">
        <el-row :gutter="20" class="profile">
          <el-col :span="6" class="profile-item meta"><div class="grid-content "></div></el-col>
          <el-col :span="6" class="profile-item"><div class="grid-content ">
            <el-image style="width: 100px; height: 100px" :src="userData.user.pic" fit="fill" />
          </div></el-col>
        </el-row>
        <el-row :gutter="20" class="profile">
          <el-col :span="6" class="profile-item meta"><div class="grid-content ">昵称：</div></el-col>
          <el-col :span="6" class="profile-item"><div class="grid-content ">{{userData.user.nickName}}</div></el-col>
        </el-row>
        <el-row :gutter="20" class="profile">
          <el-col :span="6" class="profile-item meta"><div class="grid-content ">手机号：</div></el-col>
          <el-col :span="6" class="profile-item"><div class="grid-content ">{{userData.user.mobile}}</div></el-col>
        </el-row>
        <el-row :gutter="20" class="profile">
          <el-col :span="6" class="profile-item meta"><div class="grid-content ">性别：</div></el-col>
          <el-col :span="12" class="profile-item">
            <div class="grid-content ">{{userData.user.gender}}</div>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="profile">
          <el-col :span="6" class="profile-item meta"><div class="grid-content ">生日：</div></el-col>
          <el-col :span="6" class="profile-item">
            <div class="grid-content ">{{timestampToDate(userData.user.birthday)}}</div>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="profile">
          <el-col :span="6" class="profile-item meta"><div class="grid-content ">积分：</div></el-col>
          <el-col :span="6" class="profile-item">
            <div class="grid-content ">
              {{ userData.user.points }}
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="profile" style="margin-top: 15px;">
          <el-col :span="6">&nbsp;</el-col>
          <el-col :span="12">
            <!-- <el-button size="small" type="info" icon="el-icon-back" @click="goBack()">返回</el-button> -->
            <el-button type="success" icon="Check" @click="onShowPay()" style="background-color:#c63c26;">立即签到</el-button>
            <el-button type="primary" class="black-button" @click="handleUpdate()" icon="Edit" style="background-color:#0038a7;">修改信息</el-button>
          </el-col>
        </el-row>
      </div>

      <div class="page-title">
          <span>我的积分记录</span>
      </div><!--{{ needInfo.title }}-->
      <el-table v-loading="loading" :data="listData" border element-loading-text="拼命加载中">
        <el-table-column align="center" label="时间" width="200">
          <template #default="scope">
            <div>{{ timestampToDayHM(scope.row.updateAt) }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="item" label="详情">
          <template #default="scope">
            {{ scope.row.item }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="remindContent" label="积分变动">
          <template #default="scope">
            <strong v-if="scope.row.points>0" class="green">{{ scope.row.points }}</strong>
            <strong v-if="scope.row.points<0" class="red">{{ scope.row.points }}</strong>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination background layout="prev, pager, next" v-model:page-size="queryForm.pageSize"
          v-model:current-page="queryForm.pageNo" :total="total" @current-change="getReminderInfo" />
  
      <!-- <p class="page-title">地址管理</p>
      <el-table
        size="small"
        ref="multipleTable"
        :data="addressList"
        v-loading="loading"
        border
        element-loading-text="拼命加载中"
        style="width: 100%"
      >
        <el-table-column align="center" prop="area" label="省市区">
        </el-table-column>
        <el-table-column align="center" prop="detail" label="具体地址" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" prop="contact" label="收件人"></el-table-column>
        <el-table-column align="center" prop="mobile" label="手机号"></el-table-column>
        <el-table-column align="center" label="操作">
            <template #default="scope">
                <el-button size="mini" type="danger" @click="deleteAdd(scope.row)" icon="Delete">删除</el-button>
            </template>
        </el-table-column>
      </el-table> -->
  
      <!-- 个人编辑界面 -->
      <el-dialog v-model="open" :title="title" width="500px" append-to-body>
        <el-form ref="formRef" label-width="80px" :status-icon="true" :model="form" :rules="rules">
          <el-form-item prop="mobile" label="手机号">
            <el-input v-model="form.mobile" placeholder="手机号" prefix-icon="iphone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="nickName" label="昵称">
            <el-input v-model="form.nickName" placeholder="昵称" prefix-icon="user" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="birthday" label="出生年月">
            <el-date-picker style="width:100%;"
              v-model="form.birthday"
              type="date"
              placeholder=""
            />
          </el-form-item>
          <el-form-item prop="gender" label="性别">
            <el-radio-group v-model="form.gender" size="small">
              <el-radio-button label="男" value="男" />
              <el-radio-button label="女" value="女" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="头像" prop="role">
            <el-upload 
              class="avatar-uploader showUploader"
              ref="businessLicense"
              action
              :auto-upload="false"
              :show-file-list="false"
              :on-remove="handleRemoveLogo"
              :on-change="uploadLogoFile"
            >
            <ul class="img-list">
              <li v-if="form.pic==''" class="addpic"><el-icon><Plus/></el-icon></li>
            </ul>
            </el-upload>
            <ul class="img-list" v-if="form.pic!=''">
              <li class="img-li">
                <img :src="form.pic" class="avatar aspect-fill" style="width: 250px;height: 180px;" />
                <i class="logo-remove el-icon-delete" @click="handleRemoveLogo"><el-icon><Delete /></el-icon></i>
              </li>
            </ul>
          </el-form-item>
          <el-form-item prop="pwd" class="label" label="登录密码">
            <el-input placeholder="密码" v-model="form.pwd" prefix-icon="lock" autocomplete="off"  show-password></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
  
    </div>
  </template>

<script setup lang="ts">
import { ref, reactive, nextTick, toRef, onMounted, computed } from "vue";
import baseService from "@/service/baseService";
import { getCache, setCache, removeCache } from "@/utils/cache";
import { ElMessage, ElMessageBox } from "element-plus";
import { timestampToDayHM, timestampToDate, timestampToHM,formatAmount } from "@/utils/utils"
import { fileUploader } from '@/utils/upload.js'
import { useRouter, useRoute } from 'vue-router';
import { CacheToken } from "@/constants/cacheKey";
import { useStore } from 'vuex';

const store = useStore();

const router = useRouter();
// 定义计算属性
const userData = computed(() => store.state.frontUser);
// const userData = computed(() => {
//   const userInfo = getCache(CacheToken);
//   console.log('从Cache获取的用户：', userInfo)
//   return userInfo.user
// });
const payVisible = ref(false);
/**
 * 初始化
 */
const onInit = () => {
  const userInfo = getCache(CacheToken);
  baseService.get(`/api/opera/load/user/${userInfo.user.userId}`).then((res) => {
    if (res.code === 200) {
      userInfo.user=res.data
      store.commit('setFrontLoginUser', userInfo);
    }
  });
};


// 查询参数
const queryForm = reactive({
  deptName: "",
  pageNo: 1,
  pageSize: 10
});
const route = useRoute();
// 列表内容数量
const total = ref(0);
// 列表是否加载
const loading = ref(true);
// 列表返回值
const list = ref<any[]>([]);
const addressList = ref<any[]>([]);

// 表单实例
const formRef = ref();
// 是否打开弹出框
const open = ref(false);
const openDetail = ref(false);
// 弹出框标题
const title = ref("");

const listData = ref<any[]>([]);

function goBack(){
  router.back()
}

//签到
function onShowPay() {
  baseService.get(`/api/checkin/checkin`).then((res) => {
    if (res.success) {
      ElMessage.success('签到成功')
      getReminderInfo()
    }else{
      ElMessage.error('今天已签到，请勿重复签到！')
    }
  });
}

function closeDialog() {
    payVisible.value = false
}

// 提交表单数据
let form = toRef(
  reactive({
    userId: '',
    nickName: "", pwd: "", mobile: "", birthday: '', gender: '', status: 1, pic: '',
  })
);
// 表单验证
const rules = ref({
  nickName: [{ required: true, message: "请输入", trigger: "blur" }],
  mobile: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
});

const getInfo = () => {
  // const infoId = route.query.pid
  // console.log('从路由获取参数：', route.query)
  // shopId.value = infoId  
}

/**
 * 表单重置
 */
function reset() {
  form.value = {
    userId: "",
    nickName: "", pwd: "", mobile: "", birthday: '', gender: '', status: 1, isMember: 0, pic: '', height: '', weight: ''
  };

  nextTick(() => {
    formRef.value?.resetFields();
  });
}

/**
 * 修改按钮操作
 * @param id 主键
 */
 function handleUpdate() {
  open.value = true;
  title.value = "修改"
  reset()
  const userInfo = getCache(CacheToken);
  baseService.get(`/api/opera/load/user/${userInfo.user.userId}`).then((res) => {
    if (res.code === 200) {
      form.value=res.data
    }
  });
}

/**
 * 提交按钮
 */
 function submitForm() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return;
    baseService.post(`/api/user/updateUser`, form.value).then((res) => {
      if (res.code === 200) {
        if(res.success){ElMessage.success(res.msg);}
        else{ElMessage.error(res.msg);}
        open.value = false;
        baseService.get(`/api/user/detail/${form.value.userId}`).then((res) => {
        if (res.code === 200) {
            form.value = res.data
            userData.user = res.data
            const userInfo = getCache(CacheToken);
            userInfo.user = res.data
            setCache(CacheToken, userInfo);
            location.reload();
          }
        });
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

// 上传LOGO图片
function uploadLogoFile(file: any){
    const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
    const isJPG = typeArr.indexOf(file.raw.type) !== -1;
    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isJPG) {
      ElMessage.error("只能是图片!");
      return;
    }
    if (!isLt3M) {
      ElMessage.error("上传图片大小不能超过 3MB!");
      return;
    }
    var formData = new FormData();
    formData.append("myFile", file.raw)
    fileUploader(formData).then((res) => {
      console.log('LOGO上传成功', res)
      if (res.data.errno==0) {
        form.value.pic=res.data.data[0]
      } else {
        // ElMessage.error(res.data.message);
      }
    })
  }
  // 移除LOGO图片
  function handleRemoveLogo(file: any){
    console.log('移除LOGO图片！',form.value.pic)
    form.value.pic=''
  }

  //支付，升级为会员
const onPay = () => {
  const userInfo = getCache(CacheToken);
  baseService.get(`/api/user/upgrade/${userInfo.user.userId}`).then((res) => {
      loading.value = false;
      ElMessage.success("已开通会员");
      payVisible.value = false
      window.location.reload();
  }).catch(() => {
      ElMessage.error("支付异常");
      loading.value = false;
  });
}

const getReminderInfo = () => {
    baseService.post(`/api/checkin/points`, queryForm).then((res) => {
        listData.value = res.data.records;
        total.value = res.data.totalrecord;
        loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
}


onMounted(() => {
  
});

getInfo();
getReminderInfo();
onInit();

</script>

<style scoped>
.page-title{
  font-size: 16px;
  font-weight: bold;
  color: #0038a7;
  padding-left: 5px;
  border-left: 3px solid #0038a7;
  margin: 12px 0;
}
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.profile-div{
  margin-bottom: 50px;
  font-size: 14px;
}
.profile-item{
  padding: 10px 0;
}
.profile-div .meta{
  text-align: right;
  color: #888;
}
.role-div{
  background-color: #007acc;
  color: #fff;
  display: inline-block;
  padding: 1px 10px;
  border-radius: 15px;
}
.profile .el-icon-edit-btn{
  font-size: 20px;
  padding: 0 10px;
  color: #439360;
  cursor: pointer;
}
.profile .el-icon-edit-btn:HOVER{
  color: #d77f57;
}
.del-btn{
  font-size: 20px;
  color: red; right: 10px; top: 10px;position: absolute;
  text-shadow: 1px 1px #fff;
  cursor: pointer;
}
.img-list .el-icon-plus{
  font-size: 22px;
  padding: 25px;
  border: 1px dashed #ccc;
}
.avatar-uploader .avatar{
  width: 160px;
  height: 160px;
}
.addpic{
  font-size: 22px;
  padding: 20px 25px 15px 25px;
  border: 2px dashed #ccc;
  color: #888;
  height: 68px;
}
.img-list{
  display: flex;
  flex-wrap: wrap;
}
.img-list .img-li{
  width: 260px;
  position: relative;
  margin-right: 10px;
}
.logo-remove{
  font-size: 22px;
  position: absolute;
  top: 10px;
  right: 10px;
  color: #f00;
  cursor: pointer;
  text-shadow: #000 4px 4px 5px;
}
.logo-remove .el-icon{
  box-shadow: #fff 3px 5px 6px;
  background-color: #fff;
}
.logo-remove:HOVER{
  color: #F56C6C;
}
.pay-btn{
  text-align: center;
  margin: 15px 0;
}
.cell a{
  text-decoration: none;
  color: #c35556;
}
.green{
  color: #1ea7d7;
}
.red{
  color:#c35556;
}
.cell a:hover{
  text-decoration: underline;
}
</style>